package show.me.the.money.listner;

import java.util.Date;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.apache.commons.lang.StringUtils;

import show.me.the.money.util.collect.OnlineUserInfo;
import show.me.the.money.util.collect.OnlineUserInfoCollector;


public class OnlineListner implements HttpSessionListener, HttpSessionAttributeListener {
	
	@Override
	public void attributeAdded(HttpSessionBindingEvent se) {
		if(!se.getName().equals("uid")){
			return;
		}
		String uid = (String) se.getValue();
		if(StringUtils.isEmpty(uid)){
			return;
		}
		HttpSession s = se.getSession();
		OnlineUserInfoCollector.instance().logon(
				s.getId(),
				uid, 
				(String) s.getAttribute(OnlineUserInfo.SERVER_IP), 
				(String) s.getAttribute(OnlineUserInfo.SERVER_PORT), 
				(String) s.getAttribute(OnlineUserInfo.CLIENT_IP), 
				(String) s.getAttribute(OnlineUserInfo.USER_AGENT), 
				new Date()
		);
	}
	@Override
	public void attributeReplaced(HttpSessionBindingEvent se) {
		attributeAdded(se);
	}
	@Override
	public void sessionDestroyed(HttpSessionEvent se) {
		HttpSession s = se.getSession();
		String uid = (String) s.getAttribute("uid");
		if(StringUtils.isEmpty(uid)){
			return;
		}
		OnlineUserInfoCollector.instance().leave(s.getId(), new Date(s.getLastAccessedTime()), new Date());
	}
	@Override
	public void sessionCreated(HttpSessionEvent arg0) {
	}
	@Override
	public void attributeRemoved(HttpSessionBindingEvent se) {
	}

}
